package com.itop.automator.commom;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class CommandUtils {

    private static final String TAG = "CommandUtils";

    public static CommandResult exec(String command, boolean isNeedResultMsg) {
        Logger.i(TAG, "exec:" + command);
        CommandResult cmdRsult = null;
        BufferedReader successResult = null;
        BufferedReader errorResult = null;
        int result;
        try {
            Process process = Runtime.getRuntime().exec(command);
            result = process.waitFor();
            if (isNeedResultMsg) {
                StringBuilder successMsg = new StringBuilder();
                StringBuilder errorMsg = new StringBuilder();
                successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
                errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                String s;
                while ((s = successResult.readLine()) != null) {
                    successMsg.append(s);
                }
                while ((s = errorResult.readLine()) != null) {
                    errorMsg.append(s);
                }
                cmdRsult = new CommandResult(result, errorMsg.toString(), successMsg.toString());
            }
        } catch (Exception e) {
            Logger.e(TAG, "run CMD[" + command + "]err: " + e.getMessage());
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(successResult);
            IOUtils.closeQuietly(errorResult);
        }
        return cmdRsult;
    }

    public static class CommandResult {
        public int resultCode;
        public String error;
        public String success;

        public CommandResult(int resultCode, String error, String success) {
            this.resultCode = resultCode;
            this.error = error;
            this.success = success;
        }
    }
}